<template>
  <PageWrapper>
    <BasicTable @register="register">
      <template #tableTitle>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              size: 'middle',
              icon: 'ant-design:plus-outlined',
              onClick: handleAdd.bind(null),
              auth: ['admin', 'sys:user:save'],
            },
          ]"
          :dropDownActions="[
            {
              label: '重置密码',
              icon: 'ant-design:setting-outlined',
              popConfirm: {
                title: '您确定重置这几条记录密码吗？',
                confirm: handleResetPassword.bind(null, undefined),
              },
              ifShow: mSelectedRowKeys.length > 0,
              auth: ['admin', 'sys:user:resetPassword'],
            },
            {
              label: '批量删除',
              icon: 'ant-design:delete-outlined',
              popConfirm: {
                title: '您确定删除这几条记录吗？',
                confirm: handleDelete.bind(null, undefined),
              },
              ifShow: mSelectedRowKeys.length > 0,
              auth: ['admin', 'sys:user:remove'],
            },
          ]"
        >
          <template #more>
            <a-button style="margin-left: 8px">更多操作</a-button>
          </template>
        </TableAction>
      </template>
      <template #bodyCell="{ column, record }">
        <div v-if="column.dataIndex == '__ACTION__'">
          <TableAction
            :actions="[
              {
                label: '详情',
                auth: ['admin', 'sys:user:detail'],
                onClick: handleDetail.bind(null, record),
              },
              {
                label: '编辑',
                auth: ['admin', 'sys:user:update'],
                onClick: handleEdit.bind(null, record),
              },
            ]"
            :dropDownActions="[
              {
                label: '扮演用户',
                icon: 'ant-design:play-circle-outlined',
                popConfirm: {
                  title: '是否扮演用户用户？',
                  confirm: handlePlayUser.bind(null, record),
                },
                auth: ['admin', 'sys:playUser'],
              },
              {
                label: '重置密码',
                icon: 'ant-design:setting-outlined',
                popConfirm: {
                  title: '您确定重置该条记录密码吗？',
                  confirm: handleResetPassword.bind(null, record),
                },
                auth: ['admin', 'sys:user:remove'],
              },
              {
                label: '授权角色',
                icon: 'ant-design:team-outlined',
                auth: ['admin', 'sys:user:grantRole'],
                onClick: handleGrantRole.bind(null, record),
              },
              {
                label: '锁定',
                icon: 'ant-design:lock-outlined',
                popConfirm: {
                  title: '您确定锁定该条记录吗？',
                  confirm: handelLocked.bind(null, record),
                },
                auth: ['admin', 'sys:user:locked'],
                ifShow: record.isLocked === 0,
              },
              {
                label: '取消锁定',
                icon: 'ant-design:unlock-outlined',
                popConfirm: {
                  title: '您确定取消锁定该条记录吗？',
                  confirm: handelLocked.bind(null, record),
                },
                auth: ['admin', 'sys:user:unLocked'],
                ifShow: record.isLocked === 1,
              },
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                popConfirm: {
                  title: '您确定删除该条记录吗？',
                  confirm: handleDelete.bind(null, record),
                },
                auth: ['admin', 'sys:user:remove'],
              },
            ]"
          />
        </div>
      </template>
    </BasicTable>
    <UserFormModal @register="registerModal" @success="reload" />
    <UserDetailModal @register="registerDetailModal" />
    <GrantRole @success="reload" ref="grantRoleRef" />
  </PageWrapper>
</template>
<script setup lang="ts">
  import { PageWrapper } from '@/components/Page';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useModal } from '@/components/Modal';
  import {
    sysUserPage,
    sysUserRemove,
    resetPassword,
    locked,
    unLocked,
    playUser,
  } from '@/api/sys/user';
  import { tableColumns, searchFormSchemas } from './schemas';
  import UserFormModal from './form.vue';
  import UserDetailModal from './detail.vue';
  import GrantRole from './GrantRole.vue';
  import { message } from 'ant-design-vue';
  import { ref } from 'vue';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  const mSelectedRowKeys = ref<any[]>([]);
  const grantRoleRef = ref();
  const [register, { reload, setSelectedRowKeys }] = useTable({
    rowKey: 'id',
    api: sysUserPage,
    columns: tableColumns,
    showIndexColumn: false,
    showTableSetting: true,
    useSearchForm: true,
    formConfig: {
      // 搜索表单配置
      labelWidth: 100,
      schemas: searchFormSchemas,
    },
    rowSelection: {
      type: 'checkbox',
      onChange(selectedRowKeys) {
        mSelectedRowKeys.value = selectedRowKeys;
      },
    },
    customRow: undefined,
  });
  const [registerModal, { openModal, setModalProps }] = useModal();
  const [registerDetailModal, { openModal: openDetailModal }] = useModal();
  const handleAdd = () => {
    openModal(true);
    setModalProps({
      title: '新增用户',
    });
  };
  const handleEdit = (record: any) => {
    openModal(true, {
      isUpdate: true,
      record,
    });
    setModalProps({
      title: '修改用户',
    });
  };
  const handleDetail = (record: any) => {
    openDetailModal(true, {
      record,
    });
  };
  const handleDelete = (record: any) => {
    const ids = record ? [record.id] : mSelectedRowKeys.value;
    sysUserRemove({
      ids: ids,
    }).then(() => {
      message.success('删除成功');
      setSelectedRowKeys([]);
      reload();
    });
  };
  // 重置密码
  const handleResetPassword = (record: any) => {
    const ids = record ? [record.id] : mSelectedRowKeys.value;
    resetPassword({
      ids: ids,
    }).then(() => {
      message.success('重置密码成功');
      setSelectedRowKeys([]);
    });
  };
  const handelLocked = (record: any) => {
    const ids = [record.id];
    const apiFun = record.isLocked ? unLocked : locked;
    const msg = record.isLocked ? '解锁' : '锁定';
    apiFun({
      ids: ids,
    }).then(() => {
      message.success(`${msg}成功`);
      reload();
    });
  };
  // 打开授权角色
  const handleGrantRole = (record: any) => {
    grantRoleRef.value.show(record);
  };
  // 扮演用户
  const handlePlayUser = (record: any) => {
    // TODO
    playUser({
      userId: record.id,
    }).then((data) => {
      // 设置token
      userStore.setToken(data.token);
      // 刷新页面
      window.location.reload();
    });
  };
</script>
<style lang="less" scoped></style>
